﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POI.eTransmittal.BusinessRule;
using DevExpress.Data.Filtering;
using POI.eTransmittal.Enitity;
using DevExpress.Xpo;
using System.Data;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using System.Configuration;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxCallback;

namespace POI.eTransmittal.WebApp
{
    public partial class NewIncomingTransmittal : BasePage
    {
        const string FileLocationKey = "poi.etransmittal_NewInComingTransmittal_File";
        const string ATTN_PROPERTY = "Attn";
        const string CC_PROPERTY = "Cc";
        const string TRANS_LOG = "log";
        const string UPLOADED_FILE = "poi.etransmittal_NewIncoming_Uploaded_File";
        const string CRITERIA_FAX = "poi.etransmittal_NewIncoming_FaxCriteria";
        const string SESSION_KEY_EMPLOYEE = "poi.etransmittal_NewIncoming_Emplyee";
        const string SESSION_KEY_CONTACTS_DETAILS = "poi.eTransmittal_ContactsDetail";
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Page_Init(object sender, EventArgs e)
        {
            RegisterXpodatasource(xpodsContactFrom, xpoDsContactTo, xpoDsFaxFrom, xpodsInbox, xpodstransUser);

            if (Session[CRITERIA_FAX] != null)
            {
                xpoDsFaxFrom.Criteria = Session[CRITERIA_FAX].ToString();
                xpoDsFaxFrom.DataBind();
                //      cboFaxFrom.DataBind();
            }
            //if (Session[SESSION_KEY_EMPLOYEE] != null)
            //{
            //    grdEmployee.DataSource = (DataTable)Session[SESSION_KEY_EMPLOYEE];
            //}

            if (string.IsNullOrEmpty(Request.QueryString["log"]))
            {
                CommonBusinessRules.GenerateContact(CurrentUnitOfWork);
                CommonBusinessRules.GenerateInbox(CurrentUnitOfWork);
                btnChange.Text = "Click here to upload.";
                dteReceivedDate.Date = DateTime.Now;
                //     RegisterXpodatasource(xpoDsEmployee);
            }
            else
            {
                IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, Request.QueryString["log"]);
                if (trns != null)
                {
                    lblNo.Text = trns.ID.ToString() + " (" + trns.Status + ")";
                    //  txtInbox.Text = trns.InboxName;
                    if (trns.ReceivedDate != DateTime.MinValue)
                        dteReceivedDate.Date = trns.ReceivedDate;
                    txtRemarks.Text = trns.Remarks;
                    txtSubject.Text = trns.Subject;
                    cboInbox.Text = trns.InboxName;

                    setCcId(trns.Cc);
                    setAttnId(trns.Attn);
                    cboContact.Text = trns.From;
                    bteAttn.Text = trns.AttnNames ;
                    bteCc.Text = trns.CcNames ;
                    cboContact.Text = trns.From;
                    //lnkFile.Text = trns.OriginalFileName;
                    //lnkFile.NavigateUrl = trns.GetUNC_FileLink();
                    //lnkFile.Target = "_blank";
                    //lnkFile.ClientVisible = true;
                    btnChange.Text = "Click here to upload.";
                    if (!string.IsNullOrEmpty(trns.OriginalFileName))
                    {
                        btnChange.Text = trns.OriginalFileName;
                    }
                    // lnkFile.NavigateUrl = CommonBusinessRules.GetUNC_FILE_PATH(trns);
                }
                else
                {
                    EntryIncoming.Load(this);
                    btnChange.Text = "Click here to upload.";
                }

            }
            ShowFlashMessage();
            ShowErrMessage();
        }

        internal void setCcId(string p)
        {
            if (hfTrans.Contains("cc"))
                hfTrans["cc"] = p;
            else
                hfTrans.Add("cc", p);
        }

        internal void setAttnId(string p)
        {
            if (hfTrans.Contains("attn"))
                hfTrans["attn"] = p;
            else
                hfTrans.Add("attn", p);
        }
        protected void clbOperation_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            string par = e.Parameter;
            switch (par)
            {
                case "distribute":
                    Distribute(e);
                    break;
                case "isredirect":
                    Isredirect(e);
                    break;
            }
        }

        private void Isredirect(DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            string prm = Request.QueryString["notpop"];
            if (!string.IsNullOrEmpty(Request.QueryString["notpop"]))
            {
                ASPxCallback.RedirectOnCallback("~/InquiryIncoming.aspx");
            }
            else
            {
                e.Result = "true";
            }
        }

        private void Distribute(DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            // CommonBusinessRules.RegisterIncomingtransmittAl(CurrentUnitOfWork,txtInbox.Text,txtSubject.Text,cboFrom.Text,cboTo.Text,dteReceivedDate.Date,
        }


        protected void grdEmployee_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            string[] prms = e.Parameters.Split(';');
            string param = prms[0];
            List<string> ids = new List<string>();
            if (param == "bind")
            {
                grdEmployee.Selection.UnselectAll();
                ids.AddRange(prms);
                //if (prms[1] == "attn")
                //{
                //    string attn = lblAttn.Text;
                //    ids.AddRange(attn.Split(';'));
                //}
                //else
                //{
                //    string cc = lblCc.Text;
                //    ids.AddRange(cc.Split(';'));
                //}
                foreach (string id in ids)
                {
                    if (!string.IsNullOrEmpty(id)&&id!="bind")
                        grdEmployee.Selection.SelectRowByKey(id);
                }

                //Session[SESSION_KEY_EMPLOYEE] = CommonBusinessRules.GetEmployeetable(ConfigurationManager.AppSettings["LDAP_URL"]);
                //grdEmployee.DataSource = (DataTable)Session[SESSION_KEY_EMPLOYEE];
                grdEmployee.DataBind();
            }
        }

        protected void upcDoc_FilesUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FilesUploadCompleteEventArgs e)
        {

        }
        protected override void ShowFlashMessage()
        {
            if (!string.IsNullOrEmpty(GetFlashMessage()))
            {
                stControl.HideLoading();
                popInfo.HeaderText = "Information";
                btnInfoOk.Visible = true;
                btnErrorOk.Visible = false;
                lblInfoMessage.Text = GetFlashMessage();
                popInfo.ShowOnPageLoad = true;
                ClearFlashMessage();
            }
        }
        public override void ShowErrMessage()
        {
            if (!string.IsNullOrEmpty(GetErrorMessage()))
            {
                stControl.HideLoading();
                stControl.haltAnchor = "false";
                popInfo.HeaderText = "Error";
                btnInfoOk.Visible = false;
                btnErrorOk.Visible = true;
                lblInfoMessage.Text = GetErrorMessage();
                popInfo.ShowOnPageLoad = true;
                ClearErrmessage();
            }
        }
        protected void btnDistribute_Click(object sender, EventArgs e)
        {
            saveIncoming(true);

        }

        private void HandleRedirect(int Log)
        {

            if (Request.QueryString["notpop"] == null)
                Response.Redirect("~/NewIncomingTransmittal.aspx?log=" + Log.ToString());
            else
                Response.Redirect("~/NewIncomingTransmittal.aspx?notpop=1&log=" + Log.ToString());
        }






        protected void cboFaxFrom_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            bindCboFax(e);

        }

        private void bindCboFax(DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            int dmy = -1;

            if (int.TryParse(e.Parameter, out dmy))
            {

                Session[CRITERIA_FAX] = CriteriaOperator.Parse("Contact.ID = ? and Type = ?", e.Parameter, ContactInfo.FAX).LegacyToString();
                xpoDsFaxFrom.Criteria = CriteriaOperator.Parse("Contact.ID = ? and Type = ?", e.Parameter, ContactInfo.FAX).LegacyToString();

                //    cboFaxFrom.DataBind();
            }

        }



        protected void btnInfoOk_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Main.aspx");
        }

        protected void gridContactsInfo_BeforePerformDataSelect(object sender, EventArgs e)
        {
            Session[SESSION_KEY_CONTACTS_DETAILS] = (sender as ASPxGridView).GetMasterRowKeyValue();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            saveIncoming(false);

        }

        private void saveIncoming(bool isDistributed)
        {
            int Log = string.IsNullOrEmpty(Request.QueryString["log"]) ? -1 : Convert.ToInt32(Request.QueryString["log"]);
            int step = -1;
            bool isErr = false;
            string shareFolder = "";
            stControl.HideLoading();
            try
            {
                EntryIncoming.StoreSession(this);
                string inbox = cboInbox.Text;
                DateTime receivedDate = dteReceivedDate.Date;
                string subject = txtSubject.Text;
                string remarks = txtRemarks.Text;
                string from = cboContact.Text;
                string attn = getAttnId();
                string cc = getCCid();
                UploadedFile file = upcDoc.UploadedFiles[0];
                if (string.IsNullOrEmpty(subject)||string.IsNullOrEmpty(inbox)||receivedDate.Date == DateTime.MinValue||string.IsNullOrEmpty(attn)||file.FileName=="")
                    throw new Exception("All entry is required, except Cc and remarks.");
                if (file.FileName != "")
                {
                    string ext = Path.GetExtension(file.FileName);

                    CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);
                }
                
                if (Log < 0) // kalo null atau empty berarti belum ada
                {
                    Log = CommonBusinessRules.NewIncomingTransmittal(CurrentUnitOfWork, inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks);
                   
                    if (file.FileName == "")
                    {
                        if (isDistributed)
                        {
                            step = -1;
                            throw new Exception("Please provide the document");
                        }
                    }
                    else
                    {
                      
                        
                        lblNo.Text = Log.ToString();
                        IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, Log.ToString());
                        string path = CommonBusinessRules.GetIncomingShareFolderToWrite(CurrentUnitOfWork);
                        step = 2;
                        string newFileName = CommonBusinessRules.GetIncomingTransmittalFileName(CurrentUnitOfWork, Log, Path.GetExtension(file.FileName));
                        shareFolder = Path.Combine(path, newFileName);
                        file.SaveAs(Path.Combine(path, newFileName));
                        trns.FaxFileLink = shareFolder;
                        trns.OriginalFileName = Path.GetFileName(file.FileName);
                        trns.Save();
                        CurrentUnitOfWork.CommitChanges();
                        step = -1;
                        if (isDistributed)
                        {
                            step = 3;
                            CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log, Path.Combine(path, newFileName), Path.GetFileName(file.FileName));
                        }
                    }


                }
                else
                {
                    int test = 0;
                    if (int.TryParse(Request.QueryString["log"], out test))
                    {

                        Log = test;
                         file = upcDoc.UploadedFiles[0];
                        if (file.FileName == "")
                        {
                            CommonBusinessRules.SaveIncoming(CurrentUnitOfWork, Request.QueryString["log"], inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks);
                            if (isDistributed)
                            {
                                step = 3;
                                CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log);
                            }
                        }
                        else
                        {
                            lblNo.Text = Log.ToString();
                            string ext = Path.GetExtension(file.FileName);

                            CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);
                            string path = CommonBusinessRules.GetIncomingShareFolderToWrite(CurrentUnitOfWork);
                            step = 2;
                            string newFileName = CommonBusinessRules.GetIncomingTransmittalFileName(CurrentUnitOfWork, Log, Path.GetExtension(file.FileName));
                            shareFolder = Path.Combine(path, newFileName);

                            file.SaveAs(shareFolder);

                            CommonBusinessRules.SaveIncoming(CurrentUnitOfWork, Request.QueryString["log"], inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks, shareFolder, file.FileName);
                            if (isDistributed)
                            {
                                step = 3;
                                CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log, Path.Combine(path, newFileName), Path.GetFileName(file.FileName));
                            }
                        }
                    }
                    else
                    {
                        step = -1;
                        throw new Exception("Query string is corrupted");
                    }
                }

            }
            catch (Exception ex)
            {
                isErr = true;
                switch (step)
                {
                    case 1:
                        SetErrorMessage("Unable to save data, please contact database administrator.");
                        break;
                    case 2:
                        SetErrorMessage("Unable to create the following file :<br/>" + shareFolder);
                        break;
                    case 3:
                        SetErrorMessage("Your incoming transmittal is successfully saved, but unable to distributed.<br/>"+ex.Message);
                        break;
                    default:
                        SetErrorMessage(ex.Message.Replace(Environment.NewLine, "<br/>"));
                        break;
                }
            }

            if (!isErr)
            {
                string op = isDistributed ? "distributed" : "saved";
                SetFlashMessage("Your Transmittal is " + op + " successfully.");
            }

            HandleRedirect(Log);

        }
        class EntryIncoming
        {
           
            public DateTime ReceivedDate;
            public string Remarks;
            public string Subject;
            public string Inbox;
            public string From;
            public string Attn;
            public string Cc;
            public string AttnId;
            public string CcId;
            public static void StoreSession(NewIncomingTransmittal page)
            {
                EntryIncoming incoming = new EntryIncoming();
                incoming.Attn = page.bteAttn.Text;
                incoming.Subject = page.txtSubject.Text;
                incoming.Remarks = page.txtRemarks.Text;
                incoming.ReceivedDate = page.dteReceivedDate.Date;
                incoming.Cc = page.bteCc.Text;
                incoming.Inbox = page.cboInbox.Text;
                incoming.From = page.cboContact.Text;
                incoming.AttnId = page.getAttnId();// page.lblAttn.Text;
                incoming.CcId = page.getCCid();// page.lblCc.Text;
                page.Session["Newincomingentry"] = incoming;
            }

            public static void Load(NewIncomingTransmittal page)
            {
                EntryIncoming incoming = (EntryIncoming)page.Session["Newincomingentry"];
                if (incoming != null)
                {
                    page.bteAttn.Text = incoming.Attn;
                    page.txtSubject.Text = incoming.Subject;
                    page.txtRemarks.Text = incoming.Remarks;
                    page.dteReceivedDate.Date = incoming.ReceivedDate;
                    page.bteCc.Text = incoming.Cc;
                    page.cboInbox.Text = incoming.Inbox;
                    page.cboContact.Text = incoming.From;
                    page.setCcId(incoming.CcId);
                    page.setAttnId(incoming.AttnId);
                }
            }
        }

        protected void clbCancel_Callback(object source, CallbackEventArgs e)
        {
            IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, Request.QueryString["log"]);
            if (trns != null)
            {
                e.Result = trns.OriginalFileName;
                // lnkFile.NavigateUrl = CommonBusinessRules.GetUNC_FILE_PATH(trns);
            }
            else
                e.Result = "Click here to upload.";
        }
        //end namespace

        internal string getAttnId()
        {if(hfTrans.Contains("attn"))
            return hfTrans["attn"]==null  ? "" : hfTrans["attn"].ToString();
        return "";
        }

        internal string getCCid()
        {if(hfTrans.Contains("cc"))
            return hfTrans["cc"] == null ? "" : hfTrans["cc"].ToString();
        return "";
        }
    }
}